<?php
namespace Home\Controller;
use Think\Controller;
//header("content-type:text/html;charset=utf-8");编码格式

class TuwenController extends Controller{
	public function index()
	{
		define("TOKEN", "wx2019");//define your token
		if($_GET['echostr']){
		  $wx = $this->valid();//如果发来了echostr则进行验证
		}else{
			$wx = $this->receive();//如果没有echostr，则返回消息
		}

	}

	//接口配置信息验证
	public function valid(){
       $echoStr = $_GET["echostr"];
        if($this->checkSignature()){ //调用验证字段
            echo $echoStr;
            exit;
        }
    }
    //认证消息签名认证函数
    //验证字段
    private function checkSignature(){
 
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];    
                
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
    public function receive(){
			$obj=$GLOBALS['HTTP_RAW_POST_DATA'];//接受消息
			$postSql=simplexml_load_string($obj,'SimpleXMLElement',LIBXML_NOCDATA);
			$this->logger("接受：\n".$obj);
			if(!empty($postSql)){
				switch(trim($postSql->MsgType)){
					case "text":
					$result=$this->receiveText($postSql);
					if(!empty($result)){
						echo $result;
					}else{
							$xml="<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<Content><![CDATA[%s]]></Content>
					  </xml>";
					  
					  echo $result=sprintf($xml,$postSql->FromUserName,$postSql->ToUserName,time(),$postSql->MsgType,"没有这条文本信息(⊙o⊙)…");

					}
				}
				
				
			}	
		}
		private function receiveText($postSql){
    		$content=trim($postSql->Content);
    		if(strstr($content,"你好")){//strstr模糊匹配
    			$xml="<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<Content><![CDATA[%s]]></Content>
				  </xml>";		  
				$result=sprintf($xml,$postSql->FromUserName,$postSql->ToUserName,time(),$postSql->MsgType,"hello");
					return $result;
			}else if(strstr($content,"单图文")){
				$result=$this->receiveImage($postSql);
				$this->logger("发送单图文消息：\n".$result);
					return $result;
    		}
			else if(strstr($content,"多图文")){
				$result=$this->receiveImages($postSql);
				$this->logger("发送多图文消息：\n".$result);
					return $result;
    		}
		
    	}
		
		private function receiveImage($postSql){
			$xml = "<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%s</CreateTime>
			<MsgType><![CDATA[%s]]></MsgType>
			<ArticleCount>1</ArticleCount>
			<Articles>
			<item><Title><![CDATA[%s]]></Title> 
			<Description><![CDATA[%s]]></Description>
			<PicUrl><![CDATA[%s]]></PicUrl>
			<Url><![CDATA[%s]]></Url></item>
			</Articles></xml>";	
			$result=sprintf($xml,$postSql->FromUserName,$postSql->ToUserName,time(),"news","zhangyouwu的微信开发","微信开发其实很简单","http://pic.baike.soso.com/ugc/baikepic2/5494/20170825195528-1233831972_jpg_387_310_14279.jpg/0","http://www.baidu.com");
			return $result;	
		}
		//多图文，最多8条
		private function receiveImages($postSql){
			$content=array();
			$content[]=array("Title"=>"zhangyouwu的微信开发","Description"=>"微信开发其实很简单","PicUrl"=>"http://pic.baike.soso.com/ugc/baikepic2/5494/20170825195528-1233831972_jpg_387_310_14279.jpg/0","Url"=>"http://www.baidu.com");
			$content[]=array("Title"=>"zhangyouwu的微信开发","Description"=>"微信开发其实很简单","PicUrl"=>"http://pic.baike.soso.com/ugc/baikepic2/5494/20170825195528-1233831972_jpg_387_310_14279.jpg/0","Url"=>"http://www.baidu.com");
			$content[]=array("Title"=>"zhangyouwu的微信开发","Description"=>"微信开发其实很简单","PicUrl"=>"http://pic.baike.soso.com/ugc/baikepic2/5494/20170825195528-1233831972_jpg_387_310_14279.jpg/0","Url"=>"http://www.baidu.com");
			$content[]=array("Title"=>"zhangyouwu的微信开发","Description"=>"微信开发其实很简单","PicUrl"=>"http://pic.baike.soso.com/ugc/baikepic2/5494/20170825195528-1233831972_jpg_387_310_14279.jpg/0","Url"=>"http://www.baidu.com");
	
			
			
			$str="<item>
			<Title><![CDATA[%s]]></Title> 
			<Description><![CDATA[%s]]></Description>
			<PicUrl><![CDATA[%s]]></PicUrl>
			<Url><![CDATA[%s]]></Url></item>";
			$news="";
			foreach($content as $newArray){
				$news.=sprintf($str,$newArray['Title'],$newArray['Description'],$newArray['PicUrl'],$newArray['Url']);
				}
			$xml="<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%s</CreateTime>
			<MsgType><![CDATA[%s]]></MsgType>
			<ArticleCount>%s</ArticleCount>
			<Articles>
			$news
			
			</Articles></xml>";
			$result=sprintf($xml,$postSql->FromUserName,$postSql->ToUserName,time(),"news",count($content));
			return $result;	
			
			}
		
		private function logger($content){//存储日志
			$logSize=100000;//定义日志大小
			$log="log1.txt";//定义日志名字
			if(file_exists($log)&&filesize($log)>$logSize){//如果日志存在并且大于定义的大小
				unlink($log);//删除
			}
			//文件写入1.名字2.内容，+时间防止重复3.内容往后加而不是覆盖
			file_put_contents($log,date('H:i:s')." ".$content."\n",FILE_APPEND);
		}

	
	public function index1(){
            //获取微信发送确认的参数。
            $signature = $_GET['signature'];
            $timestamp = $_GET['timestamp'];
            $nonce = $_GET['nonce'];
            $echostr = $_GET['echostr'];
            $token = TOKEN;
            $array = array($token,$timestamp,$nonce);
            sort($array);
            $str = sha1( implode($array) );
            if( $str==$signature && $echostr ){
                echo $echostr;
                exit;
            }else{
                $this->getMsg();
            }
        }

        public function getMsg(){
            //1,获取到微信推送过来post数据（xml格式）
            $postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
            //2,处理消息类型，并设置回复类型和内容
            $postObj = simplexml_load_string($postArr);

            //用户关注事件
            if( strtolower($postObj->MsgType)=='event' && strtolower($postObj->Event)=='subscribe' ){
                $Content = '北邮即兴剧团，感谢您的关注!智能回复系统期待与您对话。';
                responseText($postObj,$Content);
            }
            //普通消息回复
            //用户发送文本消息
            if( strtolower($postObj->MsgType)=='text' && strtolower($postObj->Content)=='历史消息' ){
                $array = array(
                    array(
                        'title'=>'hao123',
                        'description'=>"hao123 is very cool",
                        'picUrl'=>'https://www.baidu.com/img/bdlogo.png',
                        'url'=>'http://www.hao123.com',
                    ),
                    array('测试1', '...', 'http://static.hcoder.net/public/course_images/559505cf44c9f.png', 'http://www.hcoder.net'),
    				array('测试2', '...', 'http://static.hcoder.net/public/course_images/559505cf44c9f.png', 'http://www.hcoder.net')
                    //多图文直接添加即可！
                );
                responseNews($postObj,$array);
            }
            if( strtolower($postObj->MsgType)=='text' && strtolower($postObj->Content)!='历史消息' )
            {
                $Content = '您输入的是：'.$postObj->Content;
                responseText($postObj,$Content);
            }
            //用户发送位置信息
            if( strtolower($postObj->MsgType)=='location' ){
                $Content = '您现在所处的位置为：'.$postObj->Label.'.经度为：'.$postObj->Location_Y.'.纬度为：'.$postObj->Location_X;
                responseText($postObj,$Content);
            }
        }




}